var express = require('express');
var router = express.Router();
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken')
var svgCaptcha = require('svg-captcha');
var { userModel, identityModel, PermissionsModel } = require('../../../model/model');

// token key值
var { ACCESS_KEY, REFRESH_KEY } = require('../Logins/token_keys/keys')
// 封装创建，验证token
var { generateToken, verifyToken } = require('../Logins/generate_token/generateToken')
// token验证 中间件导入
var { short_checkAuth, length_checkAuth } = require('../Logins/verify_token/verify_Token')
/* GET home page. */


// 双token登录
router.post('/login',async (req, res) => {
  let { user, password } = req.body.data
  let data = await userModel.find({ user, password })
  if (data.length > 0) {
    let payload = {
      _id: data[0]._id,
    }
    //生成token
    let access_token = generateToken(payload, ACCESS_KEY, '1h')
    let refresh_token = generateToken(payload, REFRESH_KEY, 60 * 60 * 24 * 7)

    res.send({
      code: 200,
      msg: '登录成功',
      data: {
        access_token,
        refresh_token,
        user: data[0].user
      }
    })
  } else {
    res.send({
      code: 400,
      msg: '登录失败,账号或密码错误'
    })
  }
})



// 刷新token 当端token过期时，使用refresh_token刷新token
router.get('/refresh_token', length_checkAuth(REFRESH_KEY), async (req, res) => {
  let claim = req.claim
  let payload = {
    _id: claim._id,
  }
  let access_token = generateToken(payload, ACCESS_KEY, '1h')
  res.send({
    code: 2000,
    msg: '刷新成功',
    access_token: access_token
  })
})


//获取验证码
router.post('/go_Verification', async (req, res) => {
  const captcha = svgCaptcha.create({
    size: 4, // 验证码长度
    width: 100, // 验证码图片宽度
    height: 35, // 验证码图片高度
    fontSize: 40,   // 验证码文字大小
    noise: 1,   // 干扰线条的数量
    color: false,    // 验证码的字符是否有颜色，默认没有，也是可以通过colorFirst参数来设置
    background: '#adc'  // 验证码图片背景颜色
  });
  res.send({
    data: captcha.data,
    text: captcha.text,
    code: 200,
  })
});



// 权限渲染接口
router.get('/getPermissions', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let claim = req.claim

  let user = await userModel.find({ _id: claim._id }) //获取用户信息
  let COS = await identityModel.find({ _id: user[0].cid }) //获取用户身份
  let quan_list = await PermissionsModel.find().lean() //获取权限列表

  let list = []
  COS[0].Permissions.forEach(ID => { //获取用户权限
    quan_list.forEach(item => { //获取权限列表
      if (String(ID) == String(item._id)) { //判断权限列表是否包含用户权限
        list.push(item) //如果包含，则添加到list中
      }
    })
  })

  let quanobj = {} //创建一个空对象
  list.forEach(item => {
    quanobj[item._id] = item //将权限列表添加到空对象中
  })
  let aaa = []
  list.forEach(item => {
    if (!item.pid) {
      aaa.push(item) //如果权限列表中不存在pid，则将权限列表添加到aaa中
    } else {
      if (!quanobj[item.pid]['children']) {
        quanobj[item.pid]['children'] = [] //如果权限列表中存在pid，则将权限列表添加到children中
      }
      if (quanobj[item.pid]) {
        quanobj[item.pid]['children'].push(item) //如果权限列表中存在pid，则将权限列表添加到children中
      }
    }
  })
  res.send({
    cos_name: COS[0].identity_name,
    info_list: aaa,
    code: 200
  })
})




module.exports = router;